package initization

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"project-im/config"
	"project-im/internal/model/dao"
)

var err error

func init() {
	ViperInit()
	MysqlInit()
	RedisInit()
}
func ViperInit() {
	viper.SetConfigFile("D:\\goWork\\project-im\\dev.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		fmt.Println("读取失败")
		return
	} else {
		fmt.Println("读取成功")
	}
	err = viper.Unmarshal(&config.AppConfig)
	if err != nil {
		fmt.Println("解析失败")
		return
	} else {
		fmt.Println("解析成功")
	}
}
func MysqlInit() {
	appConfig := config.AppConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", appConfig.User, appConfig.Password, appConfig.Host, appConfig.Port, appConfig.Database)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败")
		return
	} else {
		fmt.Println("数据库连接成功")
	}
	err = config.DB.AutoMigrate(&dao.ImUser{}, &dao.ImFriend{}, &dao.ImGroup{})
	if err != nil {
		fmt.Println("迁移失败")
		return
	} else {
		fmt.Println("迁移成功")
	}
}
func RedisInit() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.AppConfig.Redis.Host,
		Password: config.AppConfig.Redis.Password,
	})
	err = config.Rdb.Ping().Err()
	if err != nil {
		fmt.Println("redis连接失败")
		fmt.Println(err)
		return
	} else {
		fmt.Println("redis连接成功")
	}
}
